package com.goodomen.garbage.web.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goodomen.garbage.common.persistence.mapper.NoticeMapper;
import com.goodomen.garbage.common.persistence.model.Notice;
import com.goodomen.garbage.web.dto.NoticeDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class NoticeService {
    
    @Resource
    private NoticeMapper noticeMapper;

    public PageInfo<Notice> selectList(int pageNum, int pageSize, NoticeDto noticeDto) {
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeDto, notice);
        return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> {noticeMapper.selectList(notice);});
    }

    public Integer insert(NoticeDto noticeDto) {
        try {
            Notice notice = new Notice();
            BeanUtils.copyProperties(noticeDto, notice);

            return noticeMapper.insertSelective(notice);
        } catch (SqlSessionException e) {
            log.error("公告新增异常 NoticeService.update()", e);
        }
        return 0;
    }

    public Integer update(NoticeDto noticeDto) {
        try {
            Notice notice = new Notice();
            BeanUtils.copyProperties(noticeDto, notice);

            return noticeMapper.updateByPrimaryKeySelective(notice);
        } catch (SqlSessionException e) {
            log.error("公告更新异常 NoticeService.update()", e);
        }
        return 0;
    }

    public Integer delete(Long id) {
        try {
            return noticeMapper.deleteByPrimaryKey(id);
        } catch (Exception e) {
            log.error("公告删除异常 NoticeService.delete()", e);
        }
        return 0;
    }
}
